import { resolve } from 'path'

import { inputConfigure } from './configs/input'
import { outputConfigure } from './configs/output'
import { pluginsConfigure } from './plugins'
import { warnConfigure } from './configs/warn'
import { CommandLineConfigure, RollifyConfigure } from './typing'
import { merge } from 'node-aux'
import { getExtraProps, useConfigList } from './utils'
import { generateTypescript } from './configs/type'
import { externalConfigure } from './configs/external'

const commonList = [
    inputConfigure,
    outputConfigure,
    externalConfigure,
    pluginsConfigure,
    warnConfigure
]

const defaultConfig: RollifyConfigure = {
    alias: {
        '@': resolve('.', './src')
    }
}

export const buildLibConfigPlugin = function (
    useConfig: RollifyConfigure,
    userParams: CommandLineConfigure
) {
    const config: any = merge(defaultConfig, useConfig)
    const comminConfig = getExtraProps(useConfig)
    const devConfig = useConfigList([...commonList].filter(Boolean), config, userParams)
    const proConfig = useConfigList([...commonList].filter(Boolean), config, userParams)
    return {
        devConfig: [
            merge(comminConfig, devConfig),
            config?.declaration
                ? generateTypescript(
                      userParams.service,
                      config,
                      devConfig?.input,
                      devConfig?.output
                  )
                : undefined
        ].filter(Boolean),
        proConfig: [
            merge(comminConfig, proConfig),
            config?.declaration
                ? generateTypescript(
                      userParams.service,
                      config,
                      proConfig?.input,
                      proConfig?.output
                  )
                : undefined
        ].filter(Boolean)
    }
}

export default buildLibConfigPlugin
